<%--
  Created by IntelliJ IDEA.
  User: root
  Date: 2021/3/21
  Time: 9:50
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isErrorPage="true"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    pageContext.setAttribute("basePath",basePath);
%>

<html>
<head>
    <title>员工列表</title>
    <%--
        Bootstrap搭建页面
    --%>
    <%--
    Web路径不以开始的相对路径，找资源，以当前资源的路径为基准，经常容易出问题
    --%>
</head>

<link rel="stylesheet" href="${basePath}static/css/bootstrap.min.css"/>
<link rel="stylesheet" href="${basePath}static/img/bootstrap-icons-1.4.0/fonts/bootstrap-icons.css">
<body>

<!-- 员工修改的模态框 -->
<div class="modal fade" id="empEditModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document" >
        <div class="modal-content" style="width:130%">
            <div class="modal-header">
                <h4 class="modal-title" id="myModal_edit_Label">员工添加</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            </div>
            <div class="modal-body">
                <form>
                    <div class="form-group row">
                        <label for="empName_input" class="col-sm-2 col-form-label">empName</label>
                        <div class="col-sm-10">
                            <p type="text" class="form-control-static" id="empName_edit_input" name="empName"></p>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="email_input" class="col-sm-2 col-form-label">email</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="email_edit_input" placeholder="100ABC@qq.com" name="email">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <fieldset class="form-group row">
                        <legend class="col-form-label col-sm-2 float-sm-left pt-0">性别</legend>
                        <div class="col-sm-10">
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="gender" id="edit_Men" value="M" checked>
                                <label class="form-check-label" for="Men">
                                    男
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="gender" id="edit_Girl" value="G">
                                <label class="form-check-label" for="Girl">
                                    女
                                </label>
                            </div>
                        </div>
                    </fieldset>
                    <div class="form-group row">
                        <label for="email_input" class="col-sm-2 col-form-label">deptName</label>
                        <div class="col-sm-5">
                            <select class="form-control" name="deptID" id="dept_edit_select">

                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="emp_edit_btn">更新</button>
            </div>
        </div>
    </div>
</div>

<!-- 员工添加的模态框 -->
<div class="modal fade" id="empAddModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document" >
        <div class="modal-content" style="width:130%">
            <div class="modal-header">
                <h4 class="modal-title" id="myModalLabel">员工添加</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            </div>
            <div class="modal-body">
                <form>
                    <div class="form-group row">
                        <label for="empName_input" class="col-sm-2 col-form-label">empName</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="empName_input" name="empName">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="email_input" class="col-sm-2 col-form-label">email</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="email_input" placeholder="100ABC@qq.com" name="email">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <fieldset class="form-group row">
                        <legend class="col-form-label col-sm-2 float-sm-left pt-0">性别</legend>
                        <div class="col-sm-10">
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="gender" id="Men" value="M" checked>
                                <label class="form-check-label" for="Men">
                                    男
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="gender" id="Girl" value="G">
                                <label class="form-check-label" for="Girl">
                                    女
                                </label>
                            </div>
                        </div>
                    </fieldset>
                    <div class="form-group row">
                        <label for="email_input" class="col-sm-2 col-form-label">deptName</label>
                        <div class="col-sm-5">
                            <select class="form-control" name="deptID" id="dept_select">

                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="emp_save_btn">保存</button>
            </div>
        </div>
    </div>
</div>

<div class="container">
    <!--标题-->
    <div class="row">
        <div class="col-md-12">
            <h1>SSM-CRUD</h1>
        </div>
    </div>
    <!--按钮-->
    <div class="row">
        <div class="col-md-4 offset-md-8">
            <button class="btn-success" id="emp_add_model">
                <svg class="bi" fill="currentColor" width="16" height="16">
                    <use xlink:href="${basePath}static/img/bootstrap-icons-1.4.0/bootstrap-icons.svg#calendar2-plus-fill"/>
                </svg>
                新增
            </button>
            <button class="btn-danger" id="emp_delete_all_btn">
                <svg class="bi" fill="currentColor" width="16" height="16">
                    <use xlink:href="${basePath}static/img/bootstrap-icons-1.4.0/bootstrap-icons.svg#calendar-x"/>
                </svg>
                删除
            </button>
        </div>
    </div>
    <!--表格数据-->
    <div class="row">
        <div class="col-md-12">
            <table class="table table-hover" id="employs_table">
                <thead>
                    <tr>
                        <th><input type="checkbox" id="check_all"/></th>
                        <th>#</th>
                        <th>empName</th>
                        <th>gender</th>
                        <th>email</th>
                        <th>deptName</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="tbody"></tbody>
            </table>
        </div>
    </div>
    <!--分页显示-->
    <div class="row">
        <!--分页文字信息-->
        <div class="col-md-6" id="page_info_area">

        </div>
        <!--分页条信息-->
        <div class="col-md-6" id="page_nav_area">

        </div>
    </div>
</div>
</body>
</html>
<script type="text/javascript" src="${basePath}static/js/jquery-3.6.0.min.js">
</script>
<!--引入样式-->
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script type="text/javascript" src="${basePath}static/js/bootstrap.js"></script>

<script type="text/javascript">

    var totalRecord;
    var currentPage;
    //1、页面加载完以后，直接发送一个ajax请求，要到分页数据
    $(function () {
        //去首页
        to_page(1);
    });
    function to_page(pn){
        $(function () {
            $.ajax({
                url:"${basePath}/EmploysForJson",
                data:"pn="+pn,
                type:"GET",
                success:function (result) {
                    //1、解析并显示员工数据
                    build_employs_table(result);
                    //2、解析并显示分页信息
                    build_page_info(result);
                    //3、解析显示分页条数据
                    build_page_nav(result);
                }
            });
        });
    }

    //2、根据数据渲染Dom页面
    $(function () {
        $.ajax({
            url:"${basePath}/EmploysForJson",
            data:"pn=1",
            type:"Get",
            success:function (result) {
                //1、解析并显示员工数据
                build_employs_table(result);
                //2、解析并显示分页信息
                build_page_info(result);
                //3、解析显示分页条数据
                build_page_nav(result);
            }
        });
    });
    
    function build_employs_table(result) {
        //清空table表格
        $('#employs_table tbody').empty();

        var employs = result.extend.PageInfo.list;

        $.each(employs,function (index,item) {
            var checkBoxId = $('<td><input type="checkbox" class="check_item"></td>');
            var empID = $("<td></td>").append(item.empId);
            var empName = $("<td></td>").append(item.empName);
            var gender = $("<td></td>").append(item.gender=='M'?'男':'女');
            var email = $("<td></td>").append(item.email);
            var deptId = $("<td></td>").append(item.department.deptId);
            var deptName = $("<td></td>").append(item.department.deptName);

            var editBtn = $('<button></button>').addClass('btn-primary btn-sm edit_btn').
            append('<svg class="bi" fill="currentColor" width="12" height="12"><use xlink:href="${basePath}static/img/bootstrap-icons-1.4.0/bootstrap-icons.svg#wrench"/></svg>').append('编辑');
            //为编辑按钮添加一个自定义的属性，来表示员工当前id
            editBtn.attr('edit_id',item.empId);
            var delBtn = $('<button></button>').addClass('btn-danger btn-sm delete_btn').
            append('<svg class="bi" fill="currentColor" width="12" height="12"><use xlink:href="${basePath}static/img/bootstrap-icons-1.4.0/bootstrap-icons.svg#calendar-x"/></svg>').append('删除');
            //为删除按钮添加一个自定义的属性来表示当前删除的员工id
            delBtn.attr('del_id',item.empId);
            var btnTD = $('<span></span>').append(editBtn).append(' ').append(delBtn);
            $("<tr></tr>").append(checkBoxId).
            append(empID).append(empName).append(gender).append(email).append(deptId).append(deptName).append(btnTD).
            appendTo('#tbody');
        });
    }
    //2、解析并显示分页信息
    function build_page_info(result){
        var pageInfo = result.extend.PageInfo;
        totalRecord = pageInfo.total;
        currentPage = pageInfo.pageNum;
        $('#page_info_area').empty();
        $('#page_info_area').append('当前'+pageInfo.pageNum+'页,总共'+pageInfo.pages+'页,'+'总记录'+pageInfo.total);
    }
    //3、解析显示分页条数据
    function build_page_nav(result) {
        $('#page_nav_area').empty();
        //page_nav_area
        var ul = $('<ul></ul>').addClass('pagination');

        const pageInfo = result.extend.PageInfo;
        //首页
        var firstPageLi = $('<li></li>').append($('<a></a>').append('首页').attr('href','#').addClass('page-link')).addClass('page-item');
        //第一页
        var prePageLi = $('<li></li>').append($('<a></a>').append('上一页').attr('href','#').addClass('page-link')).addClass('page-item');
        var nextPageLi = $('<li></li>').append($('<a></a>').addClass('page-link').append('下一页').attr('href','#')).addClass('page-item');
        var LastPageLi =  $('<li></li>').append($('<a></a>').append('末页').attr('href','#').addClass('page-link')).addClass('page-item');
        if(pageInfo.hasPreviousPage == false){
            prePageLi.addClass('disabled');
            firstPageLi.addClass('disabled');
        }else {
            //为元素添加点击翻页的事件
            //首页
            firstPageLi.click(function () {
                to_page(1);
            });
            //上一页
            prePageLi.click(function () {
                to_page(pageInfo.pageNum-1);
            });
        }
        if(pageInfo.hasNextPage == false){
            nextPageLi.addClass('disabled');
            LastPageLi.addClass('disabled');
        }else {
            //下一页
            nextPageLi.click(function () {
                to_page(pageInfo.pageNum+1);
            });
            //末页
            LastPageLi.click(function () {
                to_page(pageInfo.pages);
            });
        }



        ul.append(firstPageLi).append(prePageLi);
        //1,2,3,4,5.....
        $.each(pageInfo.navigatepageNums,function (inedx,item) {

            var numLi = $('<li></li>').append($('<a></a>').append(item).attr('href','#').addClass('page-link')).addClass('page-item');
            if (pageInfo.pageNum==item)
                numLi.addClass('active');
            numLi.click(function () {
                to_page(item);
            });
            ul.append(numLi);
        });
        //添加下一页合末页的提示
        ul.append(nextPageLi).append(LastPageLi);

        var navEle = $('<nav></nav>').append(ul);
        navEle.appendTo('#page_nav_area');
    }
    //点击新增按钮弹出模态框。
    $('#emp_add_model').click(function () {
        //清理表单数据（表单重置,表单的样式）
        reset_form('#empAddModal form');
        //发出ajax请求，查出部门信息，显示下列列表中
        getDepts('#dept_select');
        $('#empAddModal').modal({
            backdrop: 'static'
        });
    });

    var getDepts = function(ele){
        $(ele).empty();
        $.ajax({
           url:'${basePath}/Depts',
            type:'GET',
            success:function (result) {
                /*console.log(result);*/
                //新增
                $('#dept_select').append('');
                //编辑
                $('#dept_edit_select').append('');
                $.each(result.extend.depts,function(){
                    var optionEle = $('<option></option>').append(this.deptName).attr('value',this.deptId);
                    optionEle.appendTo(ele);
                });
            }
        });
    };

    $('#emp_save_btn').click(function () {
        //1、模拟框中填写得表单数据提交给服务器进行保存
        //2、要对提交给服务器的数据进行校验
        if(!validate_and_from()){
            return false;
        }
        //3、判断之前的ajax用户名是否成功
        if ($(this).attr('ajax-va')=='error'){
            show_validate_msg('#empName_input','error','用户名重复');
            return false;
        }
        //4、发送ajax请求保存员工
        $.ajax({
            url:'${basePath}/Employs',
            type:'POST',
            data: $('#empAddModal form').serialize(),
            async:false,
            success:function (result) {
                if (result.code == 100){
                    //alert(result.msg);
                    //当员工保存成功
                    //1、关闭模拟框
                    $('#empAddModal').modal('hide');
                    //2、来到最后一页
                    //发送ajax请求显示最后一页数据即可
                    //总记录数
                    to_page(totalRecord);
                }else {
                    //显示失败信息
                    console.log(result);
                    //有那个字段的错误信息就显示那个字段
                    if(undefined !=result.extend.errorFields.email){
                        show_validate_msg('#email_input','error',result.extend.errorFields.email);
                    //显示邮件错误信息
                    }
                    if(undefined != result.extend.errorFields.empName){
                    //显示员工姓名的错误信息
                        show_validate_msg('#empName_input','error',result.extend.errorFields.empName);
                    }
                }
            }
        });
    });

    function validate_and_from(){
        //1、拿到要校验数据，进行正则校验
        var empName = $('#empName_input').val();
        var regName = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})/;
        console.log(regName.test(empName));
        if(!regName.test(empName)){
            show_validate_msg('#empName_input','error','用户名可以是2-5位中文或者6-16英文和数字的组合');
            return false;
        }
        show_validate_msg('#empName_input','success','');
        var email = $('#email_input').val();
        var regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
        if(!regEmail.test(email)){
            show_validate_msg('#email_input','error','邮箱格式错误');
            return false;
        }
        show_validate_msg('#email_input','success','');

        return true;
    }

    function show_validate_msg(ele,status,msg){
        //清楚当前元素的校验状态
        $(ele).parent().removeClass('has-success has-error');
        $(ele).next('span').text('');
        if('success'==status){
            $(ele).parent().addClass('has-success');
            $(ele).next('span').text(msg);
        }else if('error'==status){
            $(ele).parent().addClass('has-error');
            $(ele).next('span').text(msg);
        }
    }

    $('#empName_input').change(function () {
        //校验用户名是否可用
        $.ajax({
            url:'${basePath}/CheckUser',
            data:'empName='+this.value,
            type:'GET',
            async:false,
            success:function (result) {
                if(result.code==100){
                    show_validate_msg('#empName_input','success',result.extend.va_msg);
                    $('#emp_save_btn').attr('ajax-va','success');
                }else {
                    show_validate_msg('#empName_input','error',result.extend.va_msg);
                    $('#emp_save_btn').attr('ajax-va','error');
                }
            }
        });
    });

    //绑定单击事件,单个删除
    $(document).on('click','.delete_btn',function () {
        //1、弹出是否删除确认框
        var empName = $(this).parents('tr').find('td:eq(2)').text();
        var id = $(this).attr('del_id');
        if(confirm("确认删除【"+empName+"】吗？")){
            //确认，发送ajax请求
            $.ajax({
                url:'${basePath}/emp/'+id,
                type:'DELETE',
                success:function (result) {
                    console.log(result);
                 debugger;
                 to_page(currentPage);
                }
            });
        }
    });


    //1、我们是按钮创建之前绑定了click，所以绑定不上
    // 1）、可以在按钮创建的时候绑定事件 2）、绑定点击.live()
    //jquery新版本没有live，使用on进行替代
    $(document).on('click','.edit_btn',function () {
        //查出员工信息，显示员工数据
        // 1、查出部门信息，并显示部门列表
        //清理表单数据（表单重置,表单的样式）
        reset_form('#empEditModal form');
        //发出ajax请求，查出部门信息，显示下列列表中
        getDepts('#dept_edit_select');
        getEmp($(this).attr('edit_id'));
        //3、把员工的id传送过去
        $('#emp_edit_btn').attr('edit_id',$(this).attr('edit_id'));
        $('#empEditModal').modal({
            backdrop: 'static'
        });

    });

    //清空表单样式及内容
function reset_form(ele){
    $(ele)[0].reset();
    //晴空表单样式
    $(ele).find('*').removeClass('has-error has-success');
    $(ele).find('.help-block').text('');
}

//查询员工信息
function getEmp(id){
    $.ajax({
        url:'${basePath}/emp/'+id,
        type:'GET',
        async:true,
        contentType:'application/x-www-form-urlencoded',
        success:function (result) {
            if(result.code==100){
               var empData = result.extend.emp;
                $('#empName_edit_input').text(empData.empName);
                $('#email_edit_input').val(empData.email);
                $('#empEditModal input[name=gender]').val([empData.gender]);
                $('#dept_edit_select').val(empData.deptID);
            }else {
                alert("获取数据失败");
            }
        }
    });
}

    //点击更新，更新员工信息
    $('#emp_edit_btn').click(function () {
        //1、验证邮箱是否合法
        var email = $('#email_edit_input').val();
        var regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
        if(!regEmail.test(email)){
            show_validate_msg('#email_edit_input','error','邮箱格式错误');
            return false;
        }
        show_validate_msg('#email_edit_input','success','');
        //2、发送更新ajax请求
        $.ajax({
            url:'${basePath}emp/'+$(this).attr('edit_id')+'/'+$('#empName_edit_input').text(),
            type:'PUT',//'POST', 获取不到实体，配置未生效
            data: $('#empEditModal form').serialize(),
            success:function (result) {
            /*alert(result.msg);*/
                //1、关闭对话框
                $('#empEditModal').modal('hide');
                //2、回到本页面
                to_page(currentPage);
            }
        })
    });

    //完成全选/全部选功能
    $('#check_all').click(function () {
        //attr获取checked是unfinished；
        //我们这些dom原生的属性,attr获取自定义属性的值
        //propo修改和读取dom原生属性的值
        $('.check_item').prop('checked',$(this).prop('checked'));

    });
    $(document).on('click','.check_item',function () {
        //判断当前是不是全选元素
        var flag = $('.check_item:checked').length == $('.check_item').length;
        //如果不是全选，则取消全选标记
        $('#check_all').prop('checked',flag);
    });

    /*点击全部删除
    * */
    $('#emp_delete_all_btn').click(function () {
        var empNames = '';
        //组装员工id
        var del_ids = '';
        $.each($('.check_item:checked'),function () {
            //this
            empNames += $(this).parents("tr").find("td:eq(2)").text()+',';
            del_ids += $(this).parents("tr").find("td:eq(1)").text()+'-';
        });
        //去除empNames多余的
        empNames = empNames.substring(0,empNames.length-1);
        del_ids = del_ids.substring(0,del_ids.length-1);
        if (confirm("确认删除【"+empNames+"】")){
            //发送 ajax请求删除
            $.ajax({
                url:'${basePath}emp/'+del_ids,
                type:'DELETE',
                async:true,
                success:function (result) {
                    alert(result.msg);
                    //回到当前页面
                    to_page(currentPage);
                }
            })
        }
    });

</script>
